package com.gupt.reggie.filter;/*
@author name
@data 2023/4/17-23:23

过滤请求：是否需要登录后访问
*/


import com.alibaba.fastjson.JSON;
import com.gupt.reggie.common.BaseContext;
import com.gupt.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (javax.servlet.http.HttpServletRequest) servletRequest;
        HttpServletResponse response = (javax.servlet.http.HttpServletResponse) servletResponse;

        //获得请求的url
        String requestURL = request.getRequestURI();

        //设置哪些请求不被校验(过滤
        String [] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断该次请求是否需要处理
            boolean check = check(urls, requestURL);
            if(check){
                log.info("该请求不需要处理：{}",requestURL);
                filterChain.doFilter(request,response);
                return;  //退出该类
            }

//        判断商家端登录状态，已登录：放行
        Object isOk = request.getSession().getAttribute("employee");
        if(isOk != null){
            log.info("用户已登录，id为：{}",request.getSession().getAttribute("employee"));

//            long id = Thread.currentThread().getId();   //验证controller filter ObjectHandler 为同一个线程
//            log.info("当前线程id为：{}",id);

            Long empId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);              //登录id存入BaseContext

            filterChain.doFilter(request,response);
            return;  //退出该类
        }

//        判断移动端登录状态，已登录：放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);              //登录id存入BaseContext

            filterChain.doFilter(request,response);
            return;  //退出该类
        }

        //未登录：返回前端
        log.info("拦截到请求：{}",requestURL);
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));   //返回给前端页面
        return;
    }

     //匹配路径是否一致
     public boolean check(String [] urls, String requestURL){
        for(String url:urls){
            boolean match = antPathMatcher.match(url, requestURL);
            if(match){
                return true;//匹配成功
            }
        }
                return false;//匹配失败
     }

}
